<template>
  <Search :schema="schema" @search="search" @reset="reset" />
  <BaseButton class="mb-20px" type="primary" @click="add">新增</BaseButton>
  <Table
    v-model:pageSize="pageSize"
    v-model:currentPage="currentPage"
    :columns="tableColums"
    :data="dataList"
    row-key="id"
    :loading="loading"
    height="600"
    sortable
    :pagination="{ total: total }"
    @register="tableRegister"
  />
  <Dialog :title="title" v-model="visible" @close="visible = false">
    <Form :schema="formItem" @register="formRegister" :rules="rules" />
    <template #footer>
      <BaseButton type="primary" @click="FormSubmit">提交</BaseButton>
      <BaseButton type="primary" @click="visible = false">取消</BaseButton>
    </template>
  </Dialog>
</template>

<script lang="tsx" setup>
import { ref } from 'vue'
import { TableColumn, Table } from '@/components/Table'
import { BaseButton } from '@/components/Button'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { FormSchema, Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { useValidator } from '@/hooks/web/useValidator'
import { formatToDateTime } from '@/utils/dateUtil'
import { innerWidth, formItemWidth } from '@/utils/styles'
import { listApi, addApi, updateApi } from '@/api/certificate'
import { ElMessage } from 'element-plus'

// ----------------------搜索区域 start----------------------------------
const schema = ref<FormSchema[]>([
  {
    field: 'name',
    component: 'Input',
    componentProps: {
      placeholder: '请输入活动名称',
      clearble: true
    }
  },
  {
    field: 'created_at',
    component: 'DatePicker',
    componentProps: {
      type: 'date',
      placeholder: '请选择创建时间',
      valueFormat: 'YYYY-MM-DD'
    }
  }
])

const searchParams = ref({})
const search = (form: any) => {
  searchParams.value = form
  currentPage.value = 1
  getList()
}

const reset = () => {
  // 将所有搜索值设置为空
  schema.value.forEach((item) => {
    item.value = ''
  })
  searchParams.value = {}
  currentPage.value = 1
  getList()
}
// ----------------------搜索区域 end------------------------------------

// ----------------------表格区域 start----------------------------------
const tableColums = ref<TableColumn[]>([
  {
    field: 'id',
    label: 'ID'
  },
  {
    field: 'name',
    label: '证书名称',
    slots: {
      default: (scope: any) => {
        return <>{scope.row.name}</>
      }
    }
  },
  {
    field: 'condition',
    label: '证书类型',
    slots: {
      default: (scope: any) => {
        return <>{scope.row.condition}</>
      }
    }
  },
  {
    field: 'type',
    label: '证书状态',
    slots: {
      default: (scope: any) => {
        return (
          <>{scope.row.type === 1 ? '帮扶证书' : scope.row.type === 2 ? '捐赠证书' : '其他证书'}</>
        )
      }
    }
  },
  {
    field: 'created_at',
    label: '创建时间',
    slots: {
      default: (scope: any) => {
        return <>{formatToDateTime(scope.row.created_at)}</>
      }
    }
  },
  {
    field: 'operations',
    label: '操作',
    width: '250px',
    show: true,
    slots: {
      default: (scope: any) => {
        return (
          <>
            <BaseButton type="primary" onClick={() => edit(scope.row)}>
              编辑
            </BaseButton>
          </>
        )
      }
    }
  }
])
// 引入tablemethods，包括getList
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    console.log('currentPage', currentPage.value, 'pageSize', pageSize.value)

    const res = await listApi({
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchParams.value
    })
    const { data } = res
    const ans = {
      list: data.items,
      total: data.total
    }
    return ans
  }
})

const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList } = tableMethods
// const { t } = useI18n()
// ----------------------表格区域 end------------------------------------

// ----------------------dialog区域 start--------------------------------
// 管理员列表标题
const title = ref('新增公告')
// 新增/修改控件
const isAdd = ref(true)
// 管理员弹窗控件
const visible = ref(false)

function add() {
  title.value = '添加公告'
  isAdd.value = true
  formItem.value.forEach((item) => {
    item.field === 'isEnabled' ? (item.value = true) : (item.value = '')
  })
  visible.value = true
}

const delPassWd = (): FormSchema[] => {
  const newItem = ref<FormSchema[]>([])
  for (const item of formItem.value) {
    newItem.value.push(item)
  }
  return newItem.value as FormSchema[]
}

function edit(e: Announcement) {
  title.value = '编辑公告'
  isAdd.value = false
  formItem.value = delPassWd()
  formItem.value.forEach((item) => {
    if (item.field === 'isEnabled') {
      item.value = e[item.field] === 0 ? false : true
    } else {
      item.value = e[item.field]
    }
  })
  visible.value = true
}
// ----------------------dialog区域 end------------------------------------
// ----------------------表单区域 start------------------------------------
// 表单提交
async function FormSubmit() {
  const res = await formMethods.getFormData()
  const resExpose = await formMethods.getElFormExpose()
  const valid = await resExpose?.validate()
  if (valid) {
    const ans = await (isAdd.value ? addApi(res) : updateApi(res))
    if (ans.code === 200) {
      ElMessage.success('操作成功')
      getList()
    }
    currentPage.value = 1
    visible.value = false
  }
}
// 表单结构
const formItem = ref<FormSchema[]>([
  {
    field: 'id',
    hidden: true
  },
  {
    field: 'name',
    label: '活动名称',
    component: 'Input',
    colProps: formItemWidth,
    componentProps: innerWidth('请输入证书名称')
  },
  {
    field: 'condition',
    label: '发放条件',
    component: 'Input',
    colProps: formItemWidth,
    componentProps: innerWidth('请输入发放条件')
  }
])
// 表单校验
const { required } = useValidator()

const rules = ref({
  name: [required('')]
})
const { formRegister, formMethods } = useForm()
// ----------------------表单区域 end------------------------------------
</script>
